import { request } from '../utils/request.js'
import store from '../store'
import { Toast, Jump } from '../utils/tools.js'
import digit from '@/uni_modules/tg-ui/libs/fn/digit.js'
import tools from '@/uni_modules/tg-ui/libs/fn/tools.js'
import md5 from 'js-md5'
import cookie from '@/utils/auth.js'
import { encrypt } from '@/utils/aes.js'
import { GetShopCar } from './Goods.js'


//登陆
export async function login(params, type = 1) {
	try {
		//不加密
		if (type == 1) {
			params.password = encrypt(params.password)
		}
		let { success, msg, data } = await request({
			url: '/Users/UserLogin',
			method: "post",
			params,
		})
		Toast(msg);
		if (success) {
			store.commit('address/CLEAR')
			store.commit("user/SET_TOKEN", data);
			// Vue.prototype.Ws.reconnect();
			GetMyAddress();
			//购物车数据
			GetShopCar();
			//基本信息
			await UserInfo();
			//多账号登录
			Jump({
				url: "/pages/home/home",
				mode: 4,
			});

			//成功
			// Jump("/pages/mine/share/share");

		}
		return success
	} catch (e) {
		console.log(e)
		return false
	}
}



export async function wxRegist(params, type = 1) {
	try {
		console.log(params)
		let res = await request({
			url: "/Users/wx_PhoneRegister",
			method: "post",
			params,
		});
		const { success, data, msg, code } = res

		if (success) {
			store.commit("user/CLEAR_INFO");
			await tools.sleep(100)
			store.commit("user/SET_TOKEN", data);

			GetMyAddress();
			GetShopCar();

			const info = await UserInfo();

			if (!info.openidWx) {
				return await wx_BindOpenId({
					authcode: params.wxCode
				})
			}
			return {
				success,
				code
			};
		}

		return {
			success,
		};
	} catch (e) {
		console.log(e);
		return {
			success: false
		};
	}
}


//小程序绑定手机号
export async function wx_BindOpenId(params) {
	try {
		return await request({
			url: "/Users/wx_BindOpenId",
			method: "post",
			params,
		});

	} catch (e) {
		console.log(e);
		return {
			success: false,
			msg: '登录失败，网络异常'
		};
	}
}

//小程序绑定手机号
export async function BindPhone(params) {
	try {
		let { success, code, data, msg } = await request({
			url: "/Users/wx_BindPhone",
			method: "post",
			params,
		});

		if (success) {
			store.commit("user/SET_TOKEN", data);
			cookie.set('InvCode', '')
			GetMyAddress();
			GetShopCar();
			const info = await UserInfo()

			return {
				success,
				data: info.data,
				code,
				msg
			};
		}
		return { success, code, data, msg }
	} catch (e) {
		console.log(e);
		return {
			success: false,
			msg: '登录失败，网络异常'
		};
	}
}


// 注册
export async function Regist(params, type = 1) {
	try {
		if (params.password) {
			params.password = encrypt(params.password);
		}
		let { success, data, msg } = await request({
			url: "/Users/Register",
			method: "post",
			params,
		});
		Toast(msg)

		if (success) {
			store.commit('user/CLEAR_INFO')
			store.commit("user/SET_TOKEN", data);
			cookie.set('InvCode', '')
			await tools.sleep(500)
			Toast(msg)
			// Vue.prototype.Ws.reconnect();
			// 注册成功
			// if (type == 1) {
			// 	Jump("/pages/login/login")
			// Jump({
			// 	url: "/pages/home/home",
			// 	mode: 4,
			// });
			// } else {
			// 	Jump("/pages/login/download/download");
			// }
		}
		return success;
	} catch (e) {
		console.log(e);
		return false;
	}
}


//isLogin    少数情况下 未登录不需要跳转登录界面  默认跳转
export async function UserInfo(isLogin = true) {
	try {
		let { success, data, msg } = await request({
			url: "/Users/Info",
			method: "post",
			mask: false,
			isLogin: isLogin,
		});
		if (success) {
			store.commit("user/SET_USERINFO", data);
			await balance();
		}
		return { success, data }
	} catch (e) {
		console.log(e);
		return false;
	}
}



// 获取余额
export async function balance(params) {
	try {
		let { data, success } = await request({
			url: '/Users/Balance',
			method: "post",
			params,
			mask: false,
		})
		if (!success) return []
		let a = {};
		data.forEach(item => {
			item.balance = digit.minus(item.balance, item.lockbalance)
			item.usable = digit.minus(item.balance, item.lockbalance2)
			a[item.coinid] = item;
		})
		store.commit('user/SET_USERBALANCE', a)
		return data
	} catch (e) {
		console.log(e)
		return false
	}
}

export async function balance2(params) {
	try {
		let { data, success } = await request({
			url: '/Users/Balance',
			method: "post",
			params,
			mask: false,
		})
		if (!success) return []
		return { data, success }
	} catch (e) {
		console.log(e)
		return false
	}
}




/**
 * 设置/重置/忘记密码
 * @param {*} params
 */
export async function SetPassword(params) {
	try {
		params.password = encrypt(params.password);
		let { success, data, code, msg } = await request({
			url: "/Users/SetPassword",
			method: "post",
			params,
		});
		Toast(msg);
		return success;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function bindInvcode(params) {
	try {
		let res = await request({
			url: "/Users/bindInvcode",
			method: "post",
			params,
		});
		if (res.success) {

			await UserInfo()
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function BindIdcard(params) {
	try {
		let res = await request({
			url: "/Users/BindIdcard",
			method: "post",
			params,
		});
		await UserInfo()
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}


export async function banklist(params) {
	try {
		let res = await request({
			url: "/Users/banklist",
			method: "post",
			params,
		});
		if (res.data) {
			const a = {}
			res.data.forEach(item => {
				a[item.id] = item
			})
			store.commit('user/SET_BANKCARD', a)
			store.commit('user/SET_BANKCARDList', res.data)
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}


export async function addEditBank(data) {
	try {
		let res = await request({
			url: "/Users/addEditBank",
			method: "post",
			data,
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}


/**
 * 设置支付密码
 * @param {*} params
 */
export async function SetPaypassword(params) {
	try {
		params.paypassword = encrypt(params.paypassword);
		let { success, data, code, msg } = await request({
			url: "/Users/SetPaypassword",
			method: "post",
			params,
		});
		Toast(msg);
		if (success) {
			await UserInfo();
		}
		return success;
	} catch (e) {
		console.log(e);
		return false;
	}
}

/**
 * 绑定邮箱
 * @param {*} params
 */
export async function setMail(params) {
	try {
		let { success, data, code, msg } = await request({
			url: "/users/setMail",
			method: "post",
			params,
		});
		Toast(msg);
		if (success) {
			await UserInfo();
		}
		return success;
	} catch (e) {
		console.log(e);
		return false;
	}
}

/**
 * 昵称和头像
 */
export async function SetHeadpic(params) {
	try {
		let { success, data, code, msg } = await request({
			url: "/Users/SetHeadpic",
			method: "post",
			params,
		});
		Toast(msg);
		if (success) {
			await UserInfo();
		}
		return success;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function SetNickname(params) {
	try {
		let { success, data, code, msg } = await request({
			url: "/Users/SetNickname",
			method: "post",
			params,
		});
		Toast(msg);
		if (success) {
			await UserInfo();
		}
		return success;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function GetMyEnergy(params) {
	try {
		let res = await request({
			url: "/Users/GetMyEnergy",
			method: "post",
			params,
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function BindAntiWithdrawAddress(params) {
	try {
		let res = await request({
			url: "/Users/BindAntiWithdrawAddress",
			method: "post",
			params,
		});
		if (res.success) {
			await UserInfo()
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function myteam(params) {
	try {
		let res = await request({
			url: "/Users/myteam",
			method: "post",
			params,
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}



export async function BindCountry(params) {
	try {
		let res = await request({
			url: "/Users/BindCountry",
			method: "post",
			params,
		});
		if (res.success) {
			await UserInfo()
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function BindEmaill(params) {
	try {
		let res = await request({
			url: "/Users/BindEmaill",
			method: "post",
			params,
		});
		Toast(res.msg)
		if (res.success) {
			await UserInfo()
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}



export async function GetMyAddress() {
	try {
		let { success, data } = await request({
			url: "/Users/GetMyAddress",
			method: "post",
		});
		//处理空情况
		const Arrs = data || [];
		let arr = {};
		Arrs.forEach(item => {
			// 默认地址时
			if (item.isdefualt == 1) {
				store.commit('address/SET_DEFAULT', item.id)
			}
			arr[item.id] = item;
		})
		if (Arrs.length <= 0) {
			store.commit('address/SET_NOWID', '')
		}
		store.commit('address/SET_OBJ', arr)
		store.commit('address/SET_LIST', Arrs)

	} catch (e) {
		console.log(e);
		return false;
	}
}


//新增地址
export async function AddEditAddress(data) {
	try {
		let res = await request({
			url: "/Users/AddEditAddress",
			method: "post",
			data
		});
		if (res.success) {
			await GetMyAddress();
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function DelAddress(data) {
	try {
		let res = await request({
			url: "/Users/DelAddress",
			method: "post",
			data
		});
		if (res.success) {
			await GetMyAddress();
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}



// 我的团队
export async function TotalTeam(params) {
	try {
		let res = await request({
			url: "/Users/teamtotal",
			method: "post",
			params
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}
// 查询服务津贴收益明细
export async function CreditDetail(params) {
	try {
		let res = await request({
			url: "/Users/CreditDetail",
			method: "post",
			params
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}



export async function Tdmf(params) {
	try {
		let res = await request({
			url: "/Users/Tdmf",
			method: "post",
			params
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}
export async function linqu(params) {
	try {
		let res = await request({
			url: "/Users/linqu",
			method: "post",
			params
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}
export async function BindAlipayaccount(params) {
	try {
		let res = await request({
			url: "/Users/BindAlipayaccount",
			method: "post",
			params
		});
		if (res.success) {
			UserInfo()
		}
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}




export async function Shopinfo(params) {
	try {
		let res = await request({
			url: "/Users/Shopinfo",
			method: "post",
			params
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function ApplyShop(data) {
	try {
		let res = await request({
			url: "/Users/ApplyShop",
			method: "post",
			data
		});
		return res;
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function turnAdrr(longitude, latitude) {
	try {
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'GET',
				url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
				data: {
					key: 'ebd6ede86473436a06cc310fb46b5474',
					location: `${longitude},${latitude}`,
					output: 'JSON',
				},
				success: (res) => {
					console.log(res)
					resolve({
						addressComponent: res.data.regeocode.addressComponent,
						formatted_address: res.data.regeocode.formatted_address,
					})
				},
				fail: r => {
					resolve(false)
					console.log(r);
				}
			});
		})
	} catch (e) {
		console.log(e);
		return false;
	}
}

export async function exit() {
	uni.showLoading({
		title: '正在退出……'
	})
	store.commit('user/REMOVE_TOKEN')
}




//资金记录
export async function UserBalanceRecord(params) {
	try {
		let res = await request({
			url: '/Trade/GetUserBalanceRecord',
			method: "post",
			params
		})
		return res
	} catch (e) {
		return false
	}
}


export async function mytotalDay(params) {
	try {
		let res = await request({
			url: '/Users/mytotalDay',
			method: "post",
			params
		})
		return res
	} catch (e) {
		return false
	}
}
export async function SetDistrict(data) {
	try {
		let res = await request({
			url: '/Users/SetDistrict',
			method: "post",
			data
		})
		return res
	} catch (e) {
		return false
	}
}